package com.atguigu.ssoserver.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * description: LoginController
 * date: 2022/12/13 22:07
 * author: MR.孙
 */
@Controller
public class LoginController {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value = "sso_token", required = false) String sso_token){
        model.addAttribute("url", url);

        if (StringUtils.isNotEmpty(sso_token)) {
            return "redirect:" + url + "?token=" + sso_token;
        }

        return "login";
    }

    /**
     * 查询用户信息
     * @param token
     * @return
     */
    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token){
        String s = stringRedisTemplate.opsForValue().get(token);
        return s;
    }


    /**
     * 处理登录请求
     * @return
     */
    @PostMapping("/doLogin")
    public String handleLogin(@RequestParam("username") String username,
                              @RequestParam("password") String password,
                              @RequestParam("url") String url,
                              HttpServletResponse response){
        //这里只是模拟单点登录的流程，不需要经过数据库比对，只是判断不为空
        if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
            //如果登录成功， 则生成token(令牌)并保存用户信息
            String uuid = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForValue().set(uuid, username);


            /**
             * 实现一次登录，处处登录的核心就是认证通过之后给浏览器留下一个痕迹，
             * 凡是访ssoserver.com这个域名的都会带上这个痕迹，通过使用cookie实现
             */
             //给浏览器留下痕迹
            Cookie sso_token = new Cookie("sso_token", uuid);
            response.addCookie(sso_token);

            return "redirect:" + url + "?token=" + uuid;
        }else {
            //登录失败
            return "login";

        }


    }


}
